import { v4 as uuid } from "uuid";

const uniqueId = (prefix = "wep") => {
  const timeStr = Date.now() + "";
  const random = (Math.random() + "").slice(2, 4);
  return `${prefix}_${random}${timeStr}`;
};

function searchTreeNodeById(node, id) {
  if (node.key === id) {
    return node;
  }
  if (node.children) {
    for (let child of node.children) {
      const found = searchTreeNodeById(child, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
}

// 模糊搜索树节点
function searchNodeByFuzzyName(node, search, result) {
  // 如果节点包含要搜索的文本，则该节点 push 到数组中
  if (
    node.isLeaf &&
    node.title.includes(search.text) &&
    (search.auth !== undefined ? node.auth === search.auth : true)
  ) {
    result.push(node);
  }
  if (node.children) {
    // 遍历其子节点
    for (let child of node.children) {
      searchNodeByFuzzyName(child, search, result);
    }
  }
  return result;
}

// 获取树所有子节点
function getTreeNodeLeaf(node, result) {
  // 如果节点包含要搜索的文本，则该节点 push 到数组中
  if (node.isLeaf) {
    result.push(node);
  }
  if (node.children) {
    // 遍历其子节点
    for (let child of node.children) {
      getTreeNodeLeaf(child, result);
    }
  }
  return result;
}

function updateTreeNodeName(node, nodeId, newNode) {
  let curNode = searchTreeNodeById(node, nodeId);
  if (curNode) {
    for (let key in newNode) {
      curNode[key] = newNode[key];
    }
    return node;
  }
  return null;
}

// 添加树节点
function addNode(node, parentId, newNode) {
  const parent = searchTreeNodeById(node, parentId);
  if (parent) {
    const id = newNode.key || uuid();
    const newNodeObj = {
      ...newNode,
      key: id,
      path: `${parent.path}/${id}`,
    };
    if (!parent.children) {
      parent.children = [newNodeObj];
    } else {
      parent.children.push(newNodeObj);
    }
    return node;
  }
  return null;
}

// 删除树节点
function removeNode(node, parentId, id) {
  const parent = searchTreeNodeById(node, parentId);
  if (parent) {
    if (parent.children) {
      const index = parent.children.findIndex((node) => node.key === id);
      if (index !== -1) {
        parent.children.splice(index, 1);
      }
    }
    return node;
  }
  return null;
}

function getRealValue(str) {
  const type = typeof str;
  const strEmpty = {
    undefined: 1,
    null: 1,
  };
  if (type === "string") {
    return strEmpty[str] ? "" : str;
  }
  return str;
}

function formartStrForLen(str = "", len = 10) {
  if (str.length < len) {
    return str;
  }
  return str.slice(0, len) + "...";
}

const arrSort = (arr = [], key) => {
  if (key) {
    arr.sort((a, b) => a[key] - b[key]); // 按照 key 进行升序排序
  } else {
    arr.sort((a, b) => a - b);
  }

  return arr;
};

export {
  uniqueId,
  arrSort,
  formartStrForLen,
  getRealValue,
  searchTreeNodeById,
  updateTreeNodeName,
  getTreeNodeLeaf,
  searchNodeByFuzzyName,
  addNode,
  removeNode,
};
